﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZEBuz.Questionnaire.Lib.Util;

namespace ZEBuz.Questionnaire.Lib.Entities
{
    public class UserAnswer
    {
        public XMLQuestion Question { get; set; }
        public XMLOption Option { get; set; }
        public int Point { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userAnswerStr"></param>
        /// <param name="fullList">将用户的答案、题目详情和选项分值计入</param>
        /// <returns></returns>
        public static List<UserAnswer> GetList(string userAnswerStr, Questionnaire qn)
        {
            if (string.IsNullOrEmpty(userAnswerStr) || qn == null) return new List<UserAnswer>();

            List<Entities.UserAnswer> userAnswers = new List<Entities.UserAnswer>();
            XMLQuestionnaire xmlqn = null;

            xmlqn = qn.QuestionnaireDTO;

            if (xmlqn != null && userAnswerStr.Length > 0)
            {
                //todo: 这儿有一处BUG， ANSWERSTR超出了数量，比如只有31题，却存在32，33，34等，需要在提交入库前控制
                string[] uquestions = userAnswerStr.Split('|');

                for (int i = 0; i < uquestions.Length && i < xmlqn.questions.Count; i++)
                {
                    string[] uoption = uquestions.ToList()[i].Split('.');
                    UserAnswer ua = userAnswers.Find(o => o.Question != null && o.Question.id == uoption[0]);

                    if (ua == null)
                    {
                        ua = new UserAnswer
                        {
                            Option = xmlqn.options.Find(o => o.id == uoption[1]),
                            Question = xmlqn.questions.Find(o => o.id == uoption[0])
                        };

                        if (ua.Question != null)
                        {
                            ua.Point = ua.Question.opsvalues[uoption[1].ToInt() - 1];
                        }

                        userAnswers.Add(ua);
                    }
                    else
                    {
                        ua.Option = xmlqn.options.Find(o => o.id == uoption[1]);
                        ua.Question = xmlqn.questions.Find(o => o.id == uoption[0]);
                        if (ua.Question != null)
                        {
                            ua.Point = ua.Question.opsvalues[uoption[1].ToInt() - 1];
                        }
                    }
                }
            }
            return userAnswers;
        }
    }
}
